package cn.stylefeng.guns.modular.system.controller;

import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.base.shiro.annotion.Permission;
import cn.stylefeng.guns.modular.system.controller.dto.DaiChongZhiTask;
import cn.stylefeng.guns.modular.system.entity.Srecharge;
import cn.stylefeng.guns.modular.system.entity.SrechargeOrderAudit;
import cn.stylefeng.guns.modular.system.mapper.SrechargeMapper;
import cn.stylefeng.guns.modular.system.model.params.SrechargeOrderAuditParam;
import cn.stylefeng.guns.modular.system.model.params.SrechargeParam;
import cn.stylefeng.guns.modular.system.model.result.SrechargeResult;
import cn.stylefeng.guns.modular.system.service.ShiRechargeTypeService;
import cn.stylefeng.guns.modular.system.service.SrechargeOrderAuditService;
import cn.stylefeng.guns.modular.system.service.SrechargeService;
import cn.stylefeng.guns.sys.core.shiro.ShiroKit;
import cn.stylefeng.guns.sys.core.util.common.SystemConstant;
import cn.stylefeng.guns.sys.core.util.utility.StatusCode;
import cn.stylefeng.guns.sys.modular.system.service.DeptService;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 控制器
 * 代充值
 * @author yl
 * @Date 2019-07-09 20:39:18
 */
@Controller
@RequestMapping("/srecharge")
public class SrechargeController extends BaseController {

    private String PREFIX = "/srecharge";

    @Autowired
    private SrechargeService srechargeService;
    @Autowired
    private SrechargeMapper srechargeMapper;
    @Resource
    private RuntimeService runtimeService;
    @Resource
    private IdentityService identityService;
    @Resource
    private TaskService taskService;
    @Autowired
    private UserService userService;
    @Autowired
    private DeptService deptService;
    @Autowired
    private SrechargeOrderAuditService srechargeOrderAuditService;


    //充值类型Service
    @Autowired
    private ShiRechargeTypeService shiRechargeTypeService;


    /**
     * 跳转到主页面
     *
     * @author yl
     * @Date 2019-07-09
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "/srecharge.html";
    }


    /**
     * 跳转到主页面
     *
     * @author yl
     * @Date 2019-07-09
     */
    @RequestMapping("/indexCheck")
    public String indexCheck() {
        return PREFIX + "/srechargeCheck.html";
    }



    /**
     * 跳转到审核页面
     *
     * @author yl
     * @Date 2019-07-09
     */
    @RequestMapping("/srecharge_shenghe")
    public String shenghe(String id,String taskId,Model model) {
        super.setAttr("id",id);
        super.setAttr("taskId",taskId);//任务id
        model.addAttribute("id",id);
        model.addAttribute("taskId",taskId);
        return PREFIX + "/srecharge_shenghe.html";
    }


    /**
     * 新增页面
     *
     * @author yl
     * @Date 2019-07-09
     */
    @RequestMapping("/add")
    public String add(Model model) {
        model.addAttribute("srecharge",shiRechargeTypeService.list());
        model.addAttribute("username",ShiroKit.getUserNotNull().getName());
        model.addAttribute("deptName",deptService.getById(ShiroKit.getUserNotNull().getDeptId()).getSimpleName());
        return PREFIX + "/srecharge_add.html";
    }

    /**
     * 编辑页面
     *
     * @author yl
     * @Date 2019-07-09
     */
    @RequestMapping("/edit")
    public String edit(Model model) {
        model.addAttribute("srecharge",shiRechargeTypeService.list());
        model.addAttribute("username",ShiroKit.getUserNotNull().getName());
        model.addAttribute("deptName",deptService.getById(ShiroKit.getUserNotNull().getDeptId()).getSimpleName());
        return PREFIX + "/srecharge_edit.html";
    }



    /**
     * 编辑页面
     *
     * @author yl
     * @Date 2019-07-09
     */
    @RequestMapping("/editCheck")
    public String editCheck(Model model,String id,String taskId) {
        model.addAttribute("srecharge",shiRechargeTypeService.list());
        model.addAttribute("username",ShiroKit.getUserNotNull().getName());
        model.addAttribute("deptName",deptService.getById(ShiroKit.getUserNotNull().getDeptId()).getSimpleName());
        model.addAttribute("id",id);
        model.addAttribute("taskId",taskId);
        return PREFIX + "/srecharge_editCheck.html";
    }



    /**
     * 新增接口
     *
     * @author yl
     * @Date 2019-07-09
     */
    @RequestMapping("/addItem")
    @ResponseBody
    public ResponseData addItem(SrechargeParam srechargeParam) throws ParseException {
        //获取系统当前时间
        Date currDate = (Date) Calendar.getInstance().getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateTime = sdf.format(currDate); //String类型
        Date date = sdf.parse(dateTime);        //Date类型
        srechargeParam.setDate(date);

        //获取当前用登录户者的id
        srechargeParam.setApplicantId(ShiroKit.getUserNotNull().getId());

        BigDecimal status = new BigDecimal(0);
        Long statuss = status.longValue();
        srechargeParam.setSrechargeStatus(statuss);
        identityService.setAuthenticatedUserId(ShiroKit.getUserNotNull().getId() + "");
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(SystemConstant.pc_daichongzhi);
        srechargeParam.setProcessInstanceId(processInstance.getId());
        this.srechargeService.add(srechargeParam);

        //开启流程
        Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
        taskService.setAssignee(task.getId(),ShiroKit.getUserNotNull().getId() +"");
        taskService.complete(task.getId());

        return ResponseData.success();
    }

    /**
     * 编辑接口
     *  修改接口
     * @author yl
     * @Date 2019-07-09
     */
    @RequestMapping("/editItem")
    @ResponseBody
    public ResponseData editItem(SrechargeParam srechargeParam) {
        int editItem = srechargeService.UpdateSrecharge(srechargeParam.getNumber(),srechargeParam.getType(),srechargeParam.getRemarks(),srechargeParam.getId());
        return ResponseData.success();
    }

    /**
     * 删除接口
     *
     * @author yl
     * @Date 2019-07-09
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ResponseData delete(SrechargeParam srechargeParam) {
        this.srechargeService.delete(srechargeParam);
        return ResponseData.success();
    }

    /**
     * 查看详情接口
     *
     * @author yl
     * @Date 2019-07-09
     */
    @RequestMapping("/detail")
    @ResponseBody
    public LayuiPageInfo detail(String id) {
        LayuiPageInfo lay = new LayuiPageInfo();
        List<SrechargeResult> detail = srechargeService.QuerySrechargeId("3");
        lay.setData(detail);
        return lay;
    }



    /**
     * 查看详情接口
     *
     * @author yl
     * @Date 2019-07-09
     */
    @RequestMapping("/detailCheck")
    @ResponseBody
    public LayuiPageInfo detailCheck(String id) {
        LayuiPageInfo lay = new LayuiPageInfo();
        List<SrechargeResult> detail = srechargeService.QuerySrechargeId("3");
        lay.setData(detail);
        return lay;
    }




    /**
     * 查询列表
     *
     * @author yl
     * @Date 2019-07-09
     */
    @ResponseBody
    @RequestMapping("/list")
    public LayuiPageInfo list(SrechargeParam srechargeParam) {
        List<Srecharge> list = srechargeService.QuerySrecharge();
        LayuiPageInfo lay = new LayuiPageInfo();
        lay.setData(list);
        return lay;
    }


    /**
     * 查询列表
     *
     * @author yl
     * @Date 2019-07-09
     */
    @ResponseBody
    @RequestMapping("/listC")
    public LayuiPageInfo listC(SrechargeParam srechargeParam) {
        List<Srecharge> list = srechargeService.QuerySrecharge();
        LayuiPageInfo lay = new LayuiPageInfo();
        lay.setData(list);
        return lay;
    }





    /**
     * 审核列表
     * @return
     */
    @ResponseBody
    @RequestMapping("/listCheck")
    public LayuiPageInfo listCheck(){

        List<Task> tasks = taskService.createTaskQuery().processDefinitionKey(SystemConstant.pc_daichongzhi).taskCandidateUser(ShiroKit.getUserNotNull().getId() +"").list();
        if (tasks.size() == 0){
            return  new LayuiPageInfo();
        }

        List<DaiChongZhiTask> daiChongZhiTasks = tasks.stream().filter(task -> srechargeService.getOne(new QueryWrapper<Srecharge>()
                .lambda().eq(Srecharge::getProcessInstanceId,task.getProcessInstanceId()))!= null).map(task -> {
            DaiChongZhiTask daiChongZhiTask = new DaiChongZhiTask();
            Srecharge srecharge = srechargeService.getOne(new QueryWrapper<Srecharge>()
            .lambda().eq(Srecharge::getProcessInstanceId,task.getProcessInstanceId()));
            BeanUtils.copyProperties(srecharge,daiChongZhiTask);
            daiChongZhiTask.setUserName(userService.getById(srecharge.getApplicantId()).getName());
            daiChongZhiTask.setDeptName(deptService.getById(userService.getById(srecharge.getApplicantId()).getDeptId()).getSimpleName());
            daiChongZhiTask.setTaskId(task.getId());
            daiChongZhiTask.setProcessInstanceId(task.getProcessInstanceId());
            return  daiChongZhiTask;
        }).collect(Collectors.toList());

        LayuiPageInfo layuiPageInfo = new LayuiPageInfo();
        layuiPageInfo.setData(daiChongZhiTasks);
        layuiPageInfo.setCount(daiChongZhiTasks.size());
        return  layuiPageInfo;
    }


    /**
     * 跳转到审核页面
     * @param id
     * @param taskId
     * @return
     */
     @RequestMapping("/checkIndex")
     public String checkIndex(Long id ,String taskId,SrechargeOrderAuditParam srechargeOrderAuditParam){

         Task task = taskService.createTaskQuery().taskId(srechargeOrderAuditParam.getTaskId()).singleResult();
        super.setAttr("id",id);
        super.setAttr("taskId",task.getId());//任务id
        return PREFIX + "/check.html";
     }


    /**
     * 审核
     * @param srechargeOrderAuditParam
     * @return
     */
     @ResponseBody
     @RequestMapping("/check")
     public ResponseData check(SrechargeOrderAuditParam srechargeOrderAuditParam,SrechargeParam srechargeParam){

         SrechargeOrderAudit srechargeOrderAudit = new SrechargeOrderAudit();
         BeanUtils.copyProperties(srechargeOrderAuditParam,srechargeOrderAudit);
         srechargeOrderAudit.setAuditTime(new Date());
         Task task = taskService.createTaskQuery().taskId(srechargeOrderAuditParam.getTaskId()).singleResult();
         srechargeOrderAudit.setProcessInstanceId(task.getProcessInstanceId());
         srechargeOrderAudit.setTaskId(task.getId());
         srechargeOrderAudit.setUserId(ShiroKit.getUserNotNull().getId());
         BigDecimal status = new BigDecimal(srechargeParam.getId());
         Long id = status.longValue();
         srechargeOrderAudit.setSrechargeId(id);
         srechargeOrderAudit.setAuditStatus(true);
         srechargeOrderAuditService.save(srechargeOrderAudit);

         Map<String,Object> map = new HashMap<>();
         map.put("status",srechargeOrderAuditParam.getAuditStatus());
         taskService.complete(task.getId(),map);
         return  ResponseData.success(200,"审核成功",srechargeOrderAudit);
     }

}


